//index.js
//获取应用实例
var app = getApp()
Page({
  data: {
    j: 1,//帧动画初始图片
    isSpeaking: false,
    voices: [],
    voiceFilePath:null,
    voiceCreateTime:"",
    englishQ:"大象、兔子、老虎和猴子",
    englishArr: ["大象、兔子、老虎、猴子", "狮子、骆驼、猫、狗", "梨、香蕉、葡萄、橘子、苹果", "五、六、七、八、九","男孩、女孩、叔叔、阿姨"]
    },
  onLoad: function () {
    var rad = (Math.random() * 100) % 5;
    var intRad = parseInt(rad);
    var radomQueston = this.data.englishArr[intRad];
    this.setData({ englishQ: radomQueston});
  },
  //手指按下
  touchdown: function () {
    var _this = this;
    speaking.call(this);
    this.setData({
      voiceFilePath: null,
      isSpeaking: true
    });
    //开始录音
    wx.startRecord({
      success: function (res) {
        //临时路径,下次进入小程序时无法正常使用
        var tempFilePath = res.tempFilePath
        console.log("tempFilePath: " + tempFilePath)
        //持久保存
        wx.saveFile({
          tempFilePath: tempFilePath,
          success: function (res) {
            //持久路径
            //本地文件存储的大小限制为 100M
            var savedFilePath = res.savedFilePath;
            console.log("savedFilePath: " + savedFilePath);

            //var voice = { filePath: savedFilePath, createTime:new Date()};
            _this.setData({ voiceFilePath: savedFilePath, voiceCreateTime:new Date()});
          }
        })
        wx.showToast({
          title: '恭喜!录音成功',
          icon: 'success',
          duration: 1000
        })
      },
      fail: function (res) {
        //录音失败
        wx.showModal({
          title: '提示',
          content: '录音的姿势不对!',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              return
            }
          }
        })
      }
    })
  },
  //手指抬起
  touchup: function () {
    console.log("手指抬起了...")
    this.setData({
      isSpeaking: false,
    })
    clearInterval(this.timer)
    wx.stopRecord()
  },
  //点击播放录音
  gotoPlay: function (e) {
    //var filePath = e.currentTarget.dataset.key;
    var filePath = this.data.voiceFilePath;
    console.info("gotoPlay filePath==" + filePath);
    wx.playVoice({
      filePath: filePath,
      success: function () {
  
      }
    });
  },
  /**
   * 提交答案
   */
  submitQuestion: function () {
    this.setData({ submitColor: 'green' });
    wx.redirectTo({
      url: '/pages/chuquan/chuquan'
    })
  }
})
//麦克风帧动画
function speaking() {
  var _this = this;
  //话筒帧动画
  var i = 1;
  this.timer = setInterval(function () {
    i++;
    i = i % 5;
    _this.setData({
      j: i
    })
  }, 200);
}